<template>
  <div class="HomeRight">
    <div class="home-right top">
      <div class="title">
        <img src="@/assets/images/icon.png" alt="" srcset="">
        <span>无人机影像</span>
      </div>
      <div class="content" style="position: relative; display: flex; justify-content: center; align-items: center">
        <el-upload
            action="string"
            :http-request="UploadTIF"
            :on-error="onError"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :show-file-list="false"
            :file-list="fileList"
            :style="{'z-index': sourceStatus === 'unknown' ? 20 : -10}"
            style="position: absolute; left: 50%; top: 40%; transform: translate(-50%, -50%); width: 260px; height: 80px; margin-bottom: 70px; display: flex; flex-direction: column; "
            v-if="sourceStatus === 'unknown'">
          <i class="el-icon-upload" style="justify-content: center; align-items: center; font-size: 40px"></i>
          <div class="el-upload__text" style="justify-content: center; align-items: center">将TIF文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" style="justify-content: center; align-items: center; font-size: 12px;
    color: #606266;">只能上传TIF/TIFF文件</div>
        </el-upload>
        <div :style="{'z-index': sourceStatus === 'uploading' ? 20 : -10}" style="position: absolute; left: 50%; top: 50%; width: 260px; height: 80px; transform: translate(-50%, -50%)">
          <el-progress :stroke-width="18" :percentage="uploadProgress"></el-progress>
          <div style="width: 100%; text-align: center">上传中</div>
        </div>
        <div :style="{'z-index': sourceStatus === 'analysis' ? 20 : -10}" style="position: absolute; left: 50%; top: 50%; width: 260px; height: 80px; transform: translate(-50%, -50%)">
          <div class="process-bar--block--step"></div>
          <div style="width: 100%; text-align: center">解析中</div>
        </div>
        <iframe :style="{'z-index': sourceStatus === 'success' ? 20 : -10}" style="position: absolute; left: 0; top: 0; border-width: 0px;" ref="wrjContent" :src="`${proxyPrefix}/wrj/wrjTemplate.html`" width="100%" height="100%"></iframe>
      </div>
    </div>
    <div class="home-right bottom">
      <div class="title">
        <img src="@/assets/images/icon.png" alt="" srcset="">
        <span>思极地图</span>
      </div>
      <div class="content">
        <div class="info">
          <div class="input-item">
            <el-select
                v-model="searchInput"
                filterable
                remote
                reserve-keyword
                placeholder="输入关键字进行定位"
                class="sgInput"
                :remote-method="remoteMethod"
                @change="changeCenter"
                :loading="searchLoading">
              <el-option
                  v-for="item in searchOptions"
                  :key="item.key"
                  :label="item.label"
                  :value="item.value">
                <span style="float: left; margin-right: 20px">{{ item.label }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.city }}</span>
              </el-option>
            </el-select>

            <div class="search-btn" @click="changeCenter(searchInput)"></div>
          </div>
        </div>
        <epgis-map
            @map-inited="mapInited"
        ></epgis-map>
      </div>
    </div>
  </div>
</template>
<script>

import EpgisMap from "@/components/EpgisMap.vue";
import {UploadTIF} from "@/api/geo";
import {_debounce} from '@/util/select-helper.js'
import {calculateCenter, convertToLatLon} from "@/util/toUTM";

export default {
  components: {EpgisMap},
  data() {
    return {
      proxyPrefix: process.env.VUE_APP_PROXY_PREFIX,
      fileList: [],
      url: '',
      // actMode: 'pan',
      actMode: '',
      // tmpWrjCoor: null,
      // tmpSgCoor: null,
      map: null,
      idx: null,
      searchLoading: false,
      colorArray: [
        "#8dff55",
        "#99d3ff",
        "#c1a5ff",
        "#00f6ff",
        "#fe7c08",
        "#ff1800",
        "#0be394",
        "#ffc300",
      ],
      sourceStatus: 'unknown',
      uploadProgress: 0,
      markerMap : new Map(),
      sourceId: null,
      sourceGeoTransform: null,
      sourceImgUrl: null,
      sourceWidth: null,
      sourceHeight: null,
      placeSearchTask: null,
      searchInput: '',
      searchOptions: [],
      isComposing: false,
      espgCode:null,
      lon:null,
      lat:null
    }
  },
  created() {
  },
  mounted() {
    this.initEpgis((epgis,sgKey,sgSecret) =>{
      this.gisName=epgis;
      this.gisName.tokenTask.login(
          sgKey,
          sgSecret
      ).then(() =>{
        this.placeSearchTask = new epgis.PlaceSearchTask();
      })
    })

    this.$refs.wrjContent.onload = () => {
      console.log('iframe 加载完成！');
      this.$refs.wrjContent.contentWindow.setVm(this);
    };

    let input = this.$el.querySelector("div.el-select.sgInput input");
    // 监听输入法开始事件
    input.addEventListener('compositionstart', () => {
      this.isComposing = true;
    });

    // 监听输入法结束事件
    input.addEventListener('compositionend', () => {
      this.isComposing = false;
    });
  },
  methods: {
    mapInited(map) {
      this.map = map;
      map.on('click', (e) => {
        if(this.actMode === 'targetCP') {
          this.addMarker(e.lngLat);
        }
      });
      map.on('mousemove', () => {
        if(this.actMode === 'targetCP') {
          map.getCanvas().style.cursor = 'crosshair';
        }
      })
    },
    initEpgis(callback){
      fetch('/api/getSJConfig') // 假设后端接口是 /api/config
          .then(response => response.json()) // 将响应数据解析为 JSON
          .then(data => {
            let linkSGScript =document.createElement("link");
            let secSGScript = document.createElement("script");
            let href = data.sgApi + '/api/epgis-1.5.0.css';
            let src = data.sgApi + '/api/epgis-js-1.5.0.min.js';
            linkSGScript.setAttribute("rel","stylesheet")
            linkSGScript.setAttribute("href",href)
            document.head.insertBefore(linkSGScript,document.head.lastChild);
            secSGScript.setAttribute("src",src)
            document.head.insertBefore(secSGScript,document.head.lastChild);
            secSGScript.onload=secSGScript.onreadystatechange=function() {
              if(!this.readyState ||this.readyState==="loaded" || this.readyState==="complete"){
                secSGScript.onload=secSGScript.onreadystatechange=null;
                if(callback && typeof callback=="function"){
                  if(typeof epgis !='undefined'){
                    callback(epgis,data.sgKey,data.sgSecret)
                  }
                }
              }
            }
          })
    },
    changeCenterBySource(result) {
      try {
        let sourceCenter = calculateCenter(result['sourceGeoTransform'], result['col'], result['row']);
        let sourceCenterLonLat = convertToLatLon(sourceCenter[0], sourceCenter[1],this.espgCode);
        this.changeCenter(sourceCenterLonLat);
      } catch (e) {}
    },
    changeCenter(val) {
      if(this.map && val) {
        this.map.flyTo({
          center: val,
          zoom: 15,
          speed: 0.8,
        });
      }
    },
    remoteMethod : _debounce(function (query) {
      console.log('remoteMethod')
      if(!this.map || this.isComposing) return;
      if(!query || query.length < 2) return;
      this.searchLoading = true;
      this.placeSearchTask.searchPlace({
        query: query,
        region: '全国'
      }).then((result) => {
        let pois = result.pois || [];
        if(pois.length == 0) return;
        this.searchOptions.length = 0;
        for (let i = 0; i < pois.length; i++) {
          let poi = pois[i];
          this.searchOptions.push({
            key: poi['id'],
            value: poi['geometry']['coordinates'],
            label: poi['text'],
            city: poi['place_name']
          });
        }
      }).finally(() => {
        this.searchLoading = false;
      })
    }, 500),
    addMarker(lngLat) {
      var marker = this.markerMap.get(this.idx);
      if(!marker) {
        //画marker点
        var container = document.createElement("div");
        container.classList.add('cross-container');

        container.style.color = this.colorArray[(this.idx - 1) % this.colorArray.length];
        var h = document.createElement("div");
        h.classList.add('horizontal-line');
        var v = document.createElement("div");
        v.classList.add('vertical-line');

        var text = document.createElement("div");
        text.classList.add('cross-number');
        text.textContent = this.idx;

        container.appendChild(h);
        container.appendChild(v);
        container.appendChild(text);
        marker = new epgis.Marker(container);
      }
      marker.setLngLat([lngLat.lng, lngLat.lat])
      .addTo(this.map);

      this.markerMap.set(this.idx, marker);
      this.actMode = '';
      this.map.getCanvas().style.removeProperty('cursor');
      this.$emit('actModeFinish', lngLat);
      // this.tmpSgCoor = [lngLat.lng, lngLat.lat];
    },
    deleteCP(index) {
      var marker = this.markerMap.get(index);
      marker && marker.remove();

      this.$refs.wrjContent.contentWindow.deleteCP(index);
    },
    sourceFileUpload(result) {
      this.$refs.wrjContent.contentWindow.sourceFileUpload(result);
    },
    tableRowClassName({row, rowIndex}) {
      if (rowIndex === 0) {
        return 'warning-row';
      }
      return '';
    },
    uploadTIFStatus(params) {
      if(params.status === 'uploading') {
        this.sourceStatus = 'uploading';
        this.uploadProgress = params.val;
      }
      else if (params.status === 'analysis'){
        this.sourceStatus = 'analysis';
      }
    },
    resetTIF() {
      this.sourceId = null;
      this.sourceGeoTransform = null;
      this.sourceWidth = null;
      this.sourceHeight = null;
      this.searchInput = '';
      this.searchOptions.length = 0;
      this.isComposing = false;
    },
    UploadTIF(param) {
      const formData = new FormData();
      let file = param.file;
      formData.append('files', file); // 将文件对象添加到 FormData 中
      this.sourceStatus = 'uploading';
      this.$emit('resetTIF');
      UploadTIF(formData, (process) => {
        this.uploadProgress = process;
        if(process >= 100) {
          this.sourceStatus = 'analysis';
        }
      }).then(res => {
        console.log('uploadTIF', res);
        let {status_code, results} = res;
        if(status_code === 200) {
          let result = results[0];
          this.$emit('uploadTIF', result);
          this.sourceId = result['tif_rawdataId'];
          this.sourceGeoTransform = JSON.parse(result['geojson']);
          this.sourceImgUrl = result['image_url'];
          this.sourceWidth = result['width'];
          this.sourceHeight = result['height'];
          this.espgCode = result['espgCode'];
          this.lon= result['lon'];
          this.lat=result['lat'];
          param.onSuccess()
        }
        else
          param.onError()
      }).catch(err => {
        param.onError()
      });
    },
    handleAvatarSuccess() {
      console.log('handleAvatarSuccess')
      this.$emit('sourceFileUpload', {
        'sourceId' : this.sourceId,
        'sourceGeoTransform' : this.sourceGeoTransform,
        'sourceImgUrl' : this.sourceImgUrl,
        'row': this.sourceHeight,
        'col': this.sourceWidth,
      })
    },
    beforeAvatarUpload() {
      // console.log(file);
    },
    onError(e) {
      console.log(e);
    },
  },
};
</script>
<style lang="scss" scoped>
.HomeRight {
  width: 100%;
  height: 100%;
  display: flex;
  gap: 5px;

  .home-right {
    width: 50%;
    height: 100%;
    background-color: #fff;
    border: 1px solid #c2d0e0;
    border-radius: 5px;
    overflow: hidden;

    .title {
      width: 100%;
      height: 35px;
      display: flex;
      align-items: center;
      background-color: #f1f1f1;

      img {
        width: 30px;
        height: 20px;
      }

      span {
        font-size: 16px;
        font-weight: bold;
        color: #313131;
        margin-left: 10px;
      }
    }

    .content {
      width: 100%;
      height: calc(100% - 35px);
      padding: 10px;
      position: relative;
      .info {
        margin-bottom: 1rem;
        border-radius: .25rem;
        position: absolute;
        top: 2rem;
        width: auto;
        min-width: 10rem;
        left: 2rem;
        z-index: 20;
        .sgInput {
          height: 40px;
          width: 200px;
          padding-left: 10px;
          cursor: default;
        }
        .search-btn {
          background: url() no-repeat 0 -76px #3385ff;
          width: 57px;
          height: 40px;
          float: right;
          border: 0;
          padding: 0;
          cursor: pointer;
          border-radius: 0 2px 2px 0;
          -webkit-box-shadow: 1px 2px 1px rgba(0, 0, 0, 0.15);
          box-shadow: 1px 2px 1px rgba(0, 0, 0, 0.15);
          margin-left: 0px;
        }

      }
    }
  }


}

.butItem {
  width: 100px;
  height: 35px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(to bottom, #6ed2cd, #30bbac);
  border-radius: 5px;
  color: #fff;
  border: 1px solid #3aa39d;
  cursor: pointer;

  img {
    width: 18px;
    margin-right: 5px;
  }

  span {
    font-size: 15px;
  }

  &:hover {
    background: #69bfba;
  }

  &:active {
    background: linear-gradient(to bottom, #6ed2cd, #30bbac);
  }
}
</style>
<style>
/* 父容器，用于定位十字 */
.cross-container {
  width: 30px;
  height: 30px;
}

/* 水平线 */
.horizontal-line {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 30px;
  height: 2px;
  background-color: currentColor;
  transform: translate(-50%, -50%);
}

/* 垂直线 */
.vertical-line {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 2px;
  height: 30px;
  background-color: currentColor;
  transform: translate(-50%, -50%);
}

.cross-number {
  position: absolute;
  top: 60%;
  left: 80%;
  font-size: 14px;
  font-family: 'PingFangSC-Regular';
  color: currentColor;
}

.content .el-upload {
  height: 100%;
  display: flex;
  flex-direction: column;
  text-align: center;
}

.process-bar--block--step {
  float: left;
  background-image: linear-gradient(-45deg, #00a19c 25%, rgba(255, 154, 26, 0) 25%, rgba(255, 154, 26, 0) 50%, #00a19c 50%, #00a19c 75%, rgba(255, 154, 26, 0) 75%);
  background-color: #d3d3d3;
  background-size: 50px 50px;
  animation: movex 3s linear infinite;
  width: 100%;
  height: 18px;
  position: relative;
}

@keyframes movex {
  0% {
    background-position: 0 0;
  }
  100% {
    background-position: 50px 50px;
  }
}
</style>
